"""
摄像头数据模型
"""
from sqlalchemy import Column, String, Float, Boolean, Text, Integer, DateTime, JSON, Index, ForeignKey
from sqlalchemy.orm import relationship
from models.base import BaseModel
from enum import Enum


class CameraStatus(str, Enum):
    """摄像头状态枚举"""
    ONLINE = "online"
    OFFLINE = "offline"
    ERROR = "error"
    MAINTENANCE = "maintenance"


class Camera(BaseModel):
    """摄像头模型"""
    __tablename__ = "cameras"
    
    # 基本信息字段
    name = Column(String(255), nullable=False, index=True, comment="设备名称")
    longitude = Column(Float, nullable=True, comment="经度")
    latitude = Column(Float, nullable=True, comment="纬度")
    height = Column(Float, default=10.0, comment="高度")
    location = Column(String(255), comment="安装位置")
    rtsp_url = Column(String(512), comment="RTSP地址")
    wvp_device_id = Column(String(100), index=True, comment="WVP-Pro设备ID")
    wvp_channel_id = Column(String(100), index=True, comment="WVP-Pro通道ID")
    device_info = Column(JSON, comment="WVP设备详细信息")
    last_sync_time = Column(DateTime, comment="最后同步时间")
    description = Column(Text, comment="设备描述")
    ai_enabled = Column(Boolean, default=False, comment="是否启用AI分析")
    status = Column(String(20), default=CameraStatus.OFFLINE, index=True, comment="设备状态")
    ai_algorithms = Column(JSON, comment="启用的AI算法配置")
    
    # 实时流处理相关字段（保留现有功能）
    stream_status = Column(String(20), default="inactive", comment="流状态: inactive, active, error, reconnecting")
    processing_fps = Column(Integer, default=3, comment="处理帧率")
    priority_level = Column(Integer, default=5, comment="优先级 1-10")
    last_frame_time = Column(DateTime, comment="最后处理帧时间")
    performance_metrics = Column(JSON, comment="性能指标")
    stream_url = Column(String(500), comment="当前流URL")
    reconnect_count = Column(Integer, default=0, comment="重连次数")
    last_error = Column(Text, comment="最后错误信息")
    
    # 关联关系
    ai_tasks = relationship("AITask", back_populates="camera", cascade="all, delete-orphan")
    ai_results = relationship("AIResult", back_populates="camera", cascade="all, delete-orphan")
    alerts = relationship("Alert", back_populates="camera", cascade="all, delete-orphan")
    
    # 添加复合索引以提高查询性能
    __table_args__ = (
        Index('idx_cameras_location', 'longitude', 'latitude'),
        Index('idx_cameras_wvp', 'wvp_device_id', 'wvp_channel_id'),
        Index('idx_cameras_status_ai', 'status', 'ai_enabled'),
    )
    
    def __repr__(self):
        return f"<Camera(id={self.id}, name='{self.name}', status='{self.status}')>"
    
    def to_3d_format(self):
        """转换为3D前端格式"""
        return {
            "id": f"cam_{self.id}",
            "name": self.name,
            "position": {
                "lng": self.longitude,
                "lat": self.latitude,
                "height": self.height
            },
            "status": self.status,
            "location": self.location,
            "rtsp_url": self.rtsp_url,
            "wvp_device_id": self.wvp_device_id,
            "wvp_channel_id": self.wvp_channel_id,
            "description": self.description,
            "ai_enabled": self.ai_enabled,
            "isFromAPI": True,
            "apiId": self.id
        }